package sdk.pay.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import java.io.File;

import sdk.pay.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2017/5/24.
 */

public class PayFileUtil {
    public static final int REQUEST_STORGE = 0x1;

    private PayFileUtil() {
        throw new RuntimeException();
    }

    public static boolean hasSDCardPermission(Context context) {
        return EasyPermissions.hasPermissions(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    public static void requestSDCardPermission(Activity activity) {
        EasyPermissions.requestPermissions(activity, "请给予存储权限", REQUEST_STORGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    public static void deleteFile(Context context, File folder) {
        if (folder != null) {
            File[] files = folder.listFiles();
            if (null != files) {
                for (File temp : files) {
                    if (temp.isFile()) {
                        temp.delete();
//                        Environment.getExternalStorageDirectory() + File.separator + QRCODE_FOLDER_NAME + File.separator + fileName
                        deleteImage(context, temp.getAbsolutePath());
                    } else {
                        deleteFile(context, temp);
                    }
                }
            }
        }
    }

    public static void createFolder(File folder) {
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    private static boolean deleteImage(Context context, String imgPath) {
        boolean result = false;
        Cursor cursor = null;
        try {
            ContentResolver resolver = context.getContentResolver();
            cursor = MediaStore.Images.Media.query(resolver, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=?",
                    new String[]{imgPath}, null);
            if (null != cursor && cursor.moveToFirst()) {
                long id = cursor.getLong(0);
                Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                Uri uri = ContentUris.withAppendedId(contentUri, id);
                int count = context.getContentResolver().delete(uri, null, null);
                result = count == 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != cursor) {
                cursor.close();
            }
        }
        return result;
    }
}
